var API = (function(){

	const apikey = '10e298292679d216c388b4b2e0eb117a';
	var token = '';
	var ttl = 0;
	var opened;
	
	function open(callback){
		$.post(
			'/api2', {
				action: 'API_open',
				key: apikey
			}, 
			function(data, textStatus, XMLHttpRequest){
				if(data && data.done == 'success'){
					var lol = new Date();
					opened = lol.getTime();
					token = data.data.api_token;
					ttl = data.data.ttl;
					callback? callback.name(callback.params) : $.noop();
				}else{
					console.log(data.reason);
					return false;
				}
			},
			'json'
		);
	};
	
	function close(callback){
		$.post(
			'/api2', {
				action: 'API_close',
				api: token
			}, 
			function(data, textStatus, XMLHttpRequest){
				if(data && data.done == 'success'){
					callback? callback.name(callback.params) : $.noop();
				}else{
					console.log(data.reason);
				}
			},
			'json'
		);
	};
	
	function isOpen(){
		if(token == ''){
			return false;
		}else{
			var lol = new Date();
			return ((lol.getTime() - opened) / 1000)<= ttl;
		}
	}

	return { // public interface
		call: function(params) {
			if(!isOpen()){
				open({name: API.call, params: params});
			}else{
				postdata = $.extend({'api': token, 'action': params.action}, params.args);
				$.post(
					'/api2', 
					postdata,
					function(data, textStatus, XMLHttpRequest){
						if(data && data.done == 'success'){
							var lol = new Date();
							opened = lol.getTime();
							var data = data.data;
							(params.onComplete)? params.onComplete(data) : $.noop();
						}else{
							console.log(data.reason);
							(params.onFailure)? params.onFailure(data) : $.noop();
							return false;
						}
					},
					'json'
				);
			}
		}
	};
})();